from django.shortcuts import render
from django.views.generic.base import View
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponseRedirect,JsonResponse
from django.urls import reverse
from django.db.models import Q
from pure_pagination import Paginator, EmptyPage, PageNotAnInteger
from django.contrib.auth.hashers import make_password
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.backends import ModelBackend
from apps.users.models import UserProfile,EmailVerifyRecord
from apps.operation.models import UserFavorite,UserCourse,UserMessage,Banner
from apps.courses.models import Course
from apps.organizations.models import CourseOrg,Teacher
from apps.users.forms import LoginForm, DyamicLoginForm,RegisterGetForm, RegisterPostForm,\
    ForgetPwdgetForm, ModifyPwdForm,ForgetPwdpostForm,UploadImageForm,UserInfoForm,ResetPwdForm,\
    SendEmailform,EmailResiterform

from utils.email_send import send_register_email,email_register_email


class CustomAuth(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        try:
            user = UserProfile.objects.get(Q(username=username)|Q(email=username))
            if user.check_password(password):
                return user
        except Exception as e:
            return None

class MessageView(LoginRequiredMixin, View):
    login_url = '/login/'
    def get(self, request, *args, **kwargs):
        user = UserProfile.objects.get(id=request.user.id)
        messages_list = user.usermessage_set.all()
        for message in messages_list:
            message.has_read = True
            message.save()
        try:
            page = request.GET.get('page', 1)
        except PageNotAnInteger:
            page = 1
        # 对课程机构数据进行分页
        p = Paginator(messages_list, per_page=5, request=request)
        message = p.page(page)
        return render(request, 'usercenter-message.html', {
            'message_list': message
        })


class EmailSendView(LoginRequiredMixin, View):
    login_url = '/login/'

    def post(self, request, *args, **kwargs):
        email_form = SendEmailform(request.POST)
        email = request.POST.get('email', '')
        if email_form.is_valid():

            send_status = email_register_email(email, 'register')
            if send_status:
                return JsonResponse({
                    'status': "success"
                })
            else:
                return JsonResponse({
                    'status': "fail",
                    'msg': "发送失败"
                })
        else:
            return JsonResponse({
                'status': "fail",
                'msg': "邮箱错误"
            })


class EmailRegisterView(LoginRequiredMixin, View):
    login_url = '/login/'

    def get(self, request, *args, **kwargs):
        forget_form = EmailResiterform(request.POST)
        return JsonResponse({forget_form})
    def post(self, request, *args, **kwargs):
        forget_form = EmailResiterform(request.POST)
        if forget_form.is_valid():
            email = request.POST.get('email', '')
            code = request.POST.get('code', '')
            all_record = EmailVerifyRecord.objects.filter(email=email,code=code)

            try:
                active = EmailVerifyRecord.objects.get(email=email,code=code).active
            except:
                active = False
            if all_record and active:
                if UserProfile.objects.filter(email=email):
                    return JsonResponse({
                        'status': "email_error",
                        'msg': "邮箱已存在"
                    })
                user = UserProfile.objects.get(id=request.user.id)
                user.email = email
                user.save()
                record = EmailVerifyRecord.objects.get(email=email,code=code)
                record.active = False
                record.save()

                return JsonResponse({
                    'status': "success"
                })
            else:
                return JsonResponse({
                    'status': "code_error",
                    'msg': "验证码错误"
                })
        else:
            return JsonResponse({
                'status': "fail",
                'msg': "参数错误"
            })

class UserTeacherOrgView(LoginRequiredMixin, View):
    login_url = '/login/'

    def get(self, request, *args, **kwargs):
        Teacher_id_list = UserFavorite.objects.filter(user=request.user,fav_type=3)

        Teachers = []
        for teacher_id in Teacher_id_list:
            teacher = Teacher.objects.get(id=teacher_id.fav_id)
            Teachers.append(teacher)
        return render(request, 'usercenter-fav-teacher.html', {
            'Teachers': Teachers
        })


class UserFavOrgView(LoginRequiredMixin, View):
    login_url = '/login/'

    def get(self, request, *args, **kwargs):
        org_id_list = UserFavorite.objects.filter(user=request.user,fav_type=2)

        Orgs = []
        for org_id in org_id_list:
            Org = CourseOrg.objects.get(id=org_id.fav_id)
            Orgs.append(Org)
        return render(request, 'usercenter-fav-org.html', {
            'Orgs': Orgs
        })

class UserFavCourseView(LoginRequiredMixin, View):
    login_url = '/login/'

    def get(self, request, *args, **kwargs):
        course_id_list = UserFavorite.objects.filter(user=request.user,fav_type=1)

        courses = []
        for course_id in course_id_list:
            course = Course.objects.get(id=course_id.fav_id)
            courses.append(course)
        return render(request, 'usercenter-fav-course.html', {
            'courses': courses
        })

class MyCourseView(LoginRequiredMixin, View):
    login_url = '/login/'

    def get(self, request, *args, **kwargs):
        courses = UserCourse.objects.filter(user=request.user)

        # courses = []
        # for course_id in course_id_list:
        #     course = Course.objects.get(id=course_id.fav_id)
        #     courses.append(course)
        return render(request, 'usercenter-mycourse.html',{
            'courses': courses
        })


class ResetpwdView(LoginRequiredMixin, View):
    login_url = '/login/'
    def post(self, request, *args, **kwargs):
        pwd_form = ResetPwdForm(request.POST)

        if pwd_form.is_valid():
            pwd1 = request.POST.get('password1', '')
            pwd2 = request.POST.get('password2', '')
            if pwd1 != pwd2:
                return JsonResponse({'msg': '两次输入密码不一致',
                                     'status': "fail"})

            user = request.user
            user.password = make_password(pwd2)
            user.save()
            return JsonResponse({
                'status': "success"
            })
        else:
            return JsonResponse({'msg': '输入错误，请正确输入密码!',
                                 'status': "fail"})



class UploadImageView(LoginRequiredMixin, View):
    login_url = '/login/'
    def post(self, request, *args, **kwargs):
        image_form = UploadImageForm(request.POST, request.FILES, instance=request.user) # 指明实例
        if image_form.is_valid():
            image_form.save()
            return JsonResponse({
                'status': "success"
            })
        else:
            return JsonResponse({
                'status': "fail"
            })
class UserCenterInfoViews(LoginRequiredMixin,View):
    login_url = '/login/'

    def get(self, request, *args, **kwargs):
        return render(request, 'usercenter-info.html')

    def post(self, request, *args, **kwargs):
        user_form = UserInfoForm(request.POST, instance=request.user)
        if user_form.is_valid():
            user_form.save()
            return JsonResponse({
                'status': "success"
            })
        else:
            return JsonResponse({
                'status': 'failure',
                'msg': '信息错误'
            })




class IndexView(View):
    def get(self, request, *args, **kwargs):
        org_list = CourseOrg.objects.all()
        search_type = 'course'
        course_list = Course.objects.filter(is_banner=False)[:6]
        banner_course = Course.objects.filter(is_banner=True)[:2]
        banners = Banner.objects.all().order_by('index')[:5]
        return render(request, 'index.html', {
                                              'org_list': org_list,
                                              'course_list': course_list,
                                              'banner_course': banner_course,
                                              'banners': banners,
                                              'search_type': search_type})
class LoginView(View):
    def get(self, request, *args, **kwargs):
        if request.user.is_authenticated:
            return HttpResponseRedirect(reverse('index'))
        login_form = DyamicLoginForm()
        next = request.GET.get('next', '')
        return render(request, "login.html",{
            "login_form": login_form,
            'next':next
        })


    def post(self, request, *args, **kwargs):

        username = request.POST.get('username', '')
        # password = request.POST.get("password", "")
        # 表单验证
        login_form = LoginForm(request.POST)

        if login_form.is_valid():
            # if not user_name:
            #     return render(request, "login.html", {"msg": "请输入用户名"})
            # if not password:
            #     return render(request, "login.html", {"msg": "请输入密码"})
            password = login_form.cleaned_data["password"]
            user = authenticate(username=username,password=password)
            try:
                is_active = user.is_active
            except:
                is_active = ''
            #查询到用户存在
            if user is not None:
                if user.is_active:

                    # 登录
                    login(request, user)
                    next = request.GET.get('next', '')
                    if next:
                        return HttpResponseRedirect(next)
                    return HttpResponseRedirect(reverse('index'))
                else:

                    return render(request, 'login.html', {'msg': '邮箱未激活，登录失败', 'login_form': login_form})
            else:

                if is_active == False:
                    return render(request, 'login.html', {'msg': '此邮箱未激活', 'login_form': login_form})
                elif is_active == '':
                    return render(request, 'login.html', {'msg': '用户名或密码错误', 'login_form': login_form})
                return render(request, 'login.html', {'msg': '用户名或密码错误', 'login_form': login_form})
        else:
            return render(request, 'login.html', {'login_form': login_form})

class LogoutView(View):
    def get(self, request, *args, **kwargs):
        logout(request)
        return HttpResponseRedirect(reverse('index'))


class RegisterView(View):
    def get(self, request, *args, **kwargs):
        register_get_form = RegisterGetForm()
        return render(request, "register.html",{
            "register_get_form":register_get_form
        })


    def post(self, request, *args, **kwargs):
        register_form = RegisterPostForm(request.POST)
        register_get_form = RegisterGetForm()
        username = request.POST.get('username', '')
        email= request.POST.get('email', '')
        if register_form.is_valid():

            # 用户已存在

            if UserProfile.objects.filter(email=email):
                try:
                    is_active = UserProfile.objects.get(email=email).is_active
                except:
                    is_active = ''
                if is_active==True:
                    return render(request, 'register.html', {'register_form': register_form,
                                                         'register_get_form': register_get_form,
                                                         'msg': '邮箱已存在'})
                elif is_active==False:
                    send_register_email(email, 'register')
                    return render(request, 'register.html', {'register_form': register_form,
                                                             'register_get_form': register_get_form,
                                                             'msg': '邮箱已存在(未激活),已重新发送邮件'})

            pass_word = request.POST.get('password', '')
            if send_register_email(email, 'register'):
                # 实例化一个 useProfile 对象

                user_profile = UserProfile.objects.create_user(username=username,password=pass_word,email=email)
                # 默认添加的用户是激活状态（is_active=1表示True），这里修改默认的状态为 False，只有用户邮箱激活后才改为True
                user_profile.is_active = False
                user_profile.save()
                return render(request,'login.html',{'msg': '注册成功,邮件已发送，请您在邮箱中激活！'})
            else:
                return render(request, 'register.html', {'msg': '邮箱错误,无法发送邮件!',
                                                         'register.html': register_form,
                                                         'register_get_form': register_get_form})

        else:
            return render(request, 'register.html', {
                'register_form': register_form,
                'register_get_form': register_get_form
            })




class ActiveView(View):  # 主要功能是修改user_profile里的is_active字段为1
    def get(self, request, active_code):
        all_reocrds = EmailVerifyRecord.objects.filter(code=active_code)
        ac = EmailVerifyRecord.objects.get(code=active_code)
        if all_reocrds and ac.active is True:
            for record in all_reocrds:
                email = record.email
                user = UserProfile.objects.get(email=email)
                if user.is_active == True:
                    return render(request, 'login.html',{'msg': '用户已激活'})
                user.is_active = True
                user.save()
        else:#如果激活链接不存在,则返回激活失败
            return render(request,"active_faild.html")
        ac = EmailVerifyRecord.objects.get(code=active_code)
        ac.active = False
        ac.save()
        message1 = '欢迎注册!本站为独角戏top的学习网站'
        message2 = '请在个人中心完善您的个人资料'
        user = UserProfile.objects.get(email=ac.email)
        messages1 = UserMessage()
        messages1.message = message1
        messages1.has_read = False
        messages1.user = user
        messages1.save()
        messages2 = UserMessage()
        messages2.message = message2
        messages2.has_read = False
        messages2.user = user
        messages2.save()
        return render(request, 'login.html',{'msg': '激活成功'})


class ForgetPwdView(View):
    """
    找回密码
    """
    def get(self,request):
        forget_form = ForgetPwdgetForm()
        return render(request,'forgetpwd.html',{'forget_form':forget_form})

    def post(self, request):
        forget_form = ForgetPwdpostForm(request.POST)
        email = request.POST.get('email', '')
        all_record = EmailVerifyRecord.objects.filter(email=email)
        if all_record:
            if forget_form.is_valid():

                send_register_email(email, 'forget')
                return render(request,'login.html',{'msg': '发送成功，请您及时修改密码',
                                                    'forget_form': forget_form})
            else:
                return render(request, 'forgetpwd.html', {'forget_form': forget_form})
        else:
            return render(request,'forgetpwd.html', {'forget_form': forget_form,
                                                     'msg': '邮箱错误,无法发送邮件!'})


class ResetView(View):
    """
    打开邮箱链接
    """
    def get(self, request, active_code):
        # 查询邮箱验证记录是否存在
        all_record = EmailVerifyRecord.objects.filter(code=active_code)
        ac = EmailVerifyRecord.objects.get(code=active_code)
        code = active_code
        if all_record and ac.active is True:
            for record in all_record:
                email = record.email
                return render(request, 'password_reset.html', {'email': email,
                                                               'code': code})

        # 验证码不对的时候跳转到激活失败页面
        else:
            return render(request, 'active_faild.html')
        return render(request, 'active_faild.html',{'msg': '链接已失效',})


class ModifyPwdView(View):
    """
    重置密码
    """
    def post(self, request):
        modify_form = ModifyPwdForm(request.POST)
        pwd1 = request.POST.get('password1', '')
        pwd2 = request.POST.get('password2', '')
        email = request.POST.get('email', '')
        code = request.POST.get('code','')


        if modify_form.is_valid():
            if pwd1 != pwd2:
                return render(request, 'password_reset.html', {'email': email, 'msg': '两次输入密码不一致'})

            user = UserProfile.objects.get(email = email)
            user.password = make_password(pwd2)
            user.save()
            ac = EmailVerifyRecord.objects.get(code=code)
            ac.active = False
            ac.save()


            return render(request, 'login.html', {'email': email, 'msg': '修改成功'})

        else:
            email = request.POST.get('email', '')
            return render(request, 'password_reset.html', {'email': email, "modify_form": modify_form})



